from datetime import datetime
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage
from django.db.models.query_utils import Q
from django.http import Http404
from core.models import Category
from ..models import Record
from core.decorators import render


@render("news/category.html")
def search(request, q='', page=1):

    q = request.REQUEST.get('q', request.session.get('last_search_request', ''))
    
    xq = q.split(" ")
    xq = "+"+" +".join(xq)    
	
    request.session['last_search_request'] = q

    categories_id = Category.objects.all().values_list('pk', flat=True)

    #records_list = Record.objects.select_related().filter(
    #    Q(status = Record.STATUS_PUBLISHED) &
    #    Q(publish_date__lte = datetime.now()) &
    #    Q(category__in = categories_id)
    #).search(xq, ['title', 'story']).order_by('-publish_date')

    ids_list = []
    ids = Record.objects.raw("select id, title from news_record where match(title) against(\"%s\" IN BOOLEAN MODE)" % q)
    for id in ids:
        ids_list.append(id.id)


    records_list = Record.objects.filter(
        Q(status = Record.STATUS_PUBLISHED) &
        Q(publish_date__lte = datetime.now()) &
        Q(pk__in = ids_list)
    ).order_by('-publish_date')

    records_list = records_list.filter(title__icontains = q)
    
    paginator = Paginator(records_list, settings.LIVE_ENGINE_NEWS_PER_PAGE)

    try:
        records = paginator.page(page)
    except EmptyPage:
        raise Http404

    return {
        'records': records,
        'q': q,
        'found': records_list.count(),
        'pagination_rule': '/search/page/1/'
    }
